#include "mainwindow.h"

/******************************************************
 *                      槽
*****************************************************/

void MainWindow::on_FindSerial_btn_clicked()
{
    ReflashSerialPort();
    msgbox("串口已刷新");
}

void MainWindow::on_CleanReceive_btn_clicked()
{
    SerialRXTolalCnt = 0;
    ui->RX->setText(QString("RX:%1").arg(SerialRXTolalCnt));
    ui->Receive_TextEdit->clear();
}

void MainWindow::on_OpenSerial_btn_clicked()
{
    // 获取串口名称
    QString com = ui->SerialSelect_box->currentText();
    // 数据位
    QString databit = ui->DataBit_lineEdit->text();
    // 停止位
    QString stopbit = ui->StopBit_lineEdit->text();
    // 校验位
    QString paritybit = ui->ParityBit_lineEdit->text();
    // 波特率
    QString baud = ui->BaudRate_box->currentText();

    // 打开串口
    int ret = OpenSerial(com, baud ,databit, stopbit, paritybit);

    if (ret >= 0)
    {
        msgbox("打开成功");
    }
    else
    {
        msgbox("打开失败");
    }
}

void MainWindow::on_CloseSerial_btn_clicked()
{
    CloseSerial();
}

void MainWindow::on_SaveReceive2File_btn_clicked()
{
    // 打开保存文件对话框，让用户选择文件名和路径
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存文件"), QDir::homePath(), tr("Text Files (*.txt);;All Files (*)"));

    if (!fileName.isEmpty())
    {
        // 用户选择了文件名和路径，现在可以在这里写入文件
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file);
            out << ui->Receive_TextEdit->toPlainText();
            file.close();
            QMessageBox::information(this, tr("保存成功"), tr("文件已成功保存到:\n%1").arg(fileName));
        }
        else
        {
            QMessageBox::warning(this, tr("错误"), tr("无法打开文件进行写入:\n%1").arg(fileName));
        }
    }
}
void MainWindow::on_Send_btn_clicked()
{
    if (!serial->isOpen())
    {
        msgbox("请打开串口");
        return ;
    }
    QString data = ui->Send_TextEdit->toPlainText();

    // 将QString转换为QByteArray
    QByteArray dataBytes;

    // 发送回车 (\r\n) 转换为hex发送
    if (ui->RN_checkBox->isChecked())
        dataBytes = (ui->HexSend_checkBox->isChecked() ? data.toUtf8().toHex() : data.toUtf8()) + "\r\n";
    else
        dataBytes = (ui->HexSend_checkBox->isChecked() ? data.toUtf8().toHex() : data.toUtf8());

    // 计算发送总数
    int ret = serial->write(dataBytes);
    SerialTXTolalCnt += ret;
    ui->TX->setText(QString("TX:%1").arg(SerialTXTolalCnt));
}

void MainWindow::on_multi_send_stateChanged(int arg)
{
    HideMultiSend(arg);
}

void MainWindow::on_Clean_btn_clicked()
{
    SerialTXTolalCnt = 0;
    ui->TX->setText(QString("TX:%1").arg(SerialTXTolalCnt));
    ui->Send_TextEdit->clear();
}

void MainWindow::on_Send_btn_1_clicked()
{
    QString text = ui->lineEdit_1->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_1_clicked()
{
    ui->lineEdit_1->clear();
}

void MainWindow::on_Send_btn_2_clicked()
{
    QString text = ui->lineEdit_2->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_2_clicked()
{
    ui->lineEdit_2->clear();
}

void MainWindow::on_Send_btn_3_clicked()
{
    QString text = ui->lineEdit_3->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_3_clicked()
{
    ui->lineEdit_3->clear();
}

void MainWindow::on_Send_btn_4_clicked()
{
    QString text = ui->lineEdit_4->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_4_clicked()
{
    ui->lineEdit_4->clear();
}

void MainWindow::on_Send_btn_5_clicked()
{
    QString text = ui->lineEdit_5->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_5_clicked()
{
    ui->lineEdit_5->clear();
}

void MainWindow::on_Send_btn_6_clicked()
{
    QString text = ui->lineEdit_6->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_6_clicked()
{
    ui->lineEdit_6->clear();
}

void MainWindow::on_Send_btn_7_clicked()
{
    QString text = ui->lineEdit_7->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_7_clicked()
{
    ui->lineEdit_7->clear();
}

void MainWindow::on_Send_btn_8_clicked()
{
    QString text = ui->lineEdit_8->text();
    SerialWrite(&text);
}

void MainWindow::on_Clean_btn_8_clicked()
{
    ui->lineEdit_8->clear();
}

void MainWindow::on_SelectFile_btn_clicked()
{
    // 打开保存文件对话框，让用户选择文件名和路径
    QString fileName = QFileDialog::getOpenFileName(this, tr("从本地读取"), QDir::homePath(), tr("Text Files (*.txt);;All Files (*)"));

    if (!fileName.isEmpty())
    {
        // 用户选择了文件名和路径，现在可以在这里写入文件
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            ui->Send_TextEdit->setPlainText(in.readAll());
            file.close();
//            QMessageBox::information(this, tr("保存成功"), tr("文件已成功保存到:\n%1").arg(fileName));
        }
        else
        {
            QMessageBox::warning(this, tr("错误"), tr("无法打开文件进行读取:\n%1").arg(fileName));
        }
    }
}
void MainWindow::on_Find_checkBox_stateChanged(int arg)
{
    if (arg == 0)
    {
        ChangeReceivePlainTextEditAllStringColor(ui->Receive_TextEdit);//恢复颜色
    }
    if (arg && ui->Find_lineEdit->text().size()>0)
    {
        ChangeReceivePlainTextEditSubStringColor(ui->Receive_TextEdit, ui->Find_lineEdit);
    }
}

void MainWindow::on_Lisen_btn_clicked()
{
    QString ip = ui->IP_comboBox->currentText();
    int port = ui->PORT_lineEdit->text().toInt();
    if (ui->NetMode_comboBox->currentText() == "TcpServer")
    {
        if (ui->Lisen_btn->text() == "停止监听")
        {
            // 假设你有一个存储所有 QTcpSocket 对象的列表
            QList<QTcpSocket*> sockets = TcpServer->findChildren<QTcpSocket*>();
            // 关闭所有 QTcpSocket 对象
            for (QTcpSocket *socket : sockets) {
                socket->close();
            }
            // 最后关闭 QTcpServer
            TcpServer->close();
            if (!TcpServer->isListening()) {
                msgbox("服务器已停止监听");
                ui->Lisen_btn->setText("监听");
                ui->NetMode_comboBox->setEnabled(true);
            }
            delete TcpServer;
            TcpServer = nullptr;
            return ;
        }
        TcpServer = new QTcpServer;
        if (!TcpServer->isListening()) {
            if (TcpServerStart(ip, port)) {
                msgbox("服务器正在监听:" + ip + ":" + ui->PORT_lineEdit->text());
                if (ui->Lisen_btn->text() == "监听")
                {
                    ui->Lisen_btn->setText("停止监听");
                    ui->NetMode_comboBox->setEnabled(false);
                }
                SaveIpToBox();
            } else {
                msgbox("监听失败:" + TcpServer->errorString());
            }
        }
        return ;
    }
    else if (ui->NetMode_comboBox->currentText() == "TcpClient")
    {
        if (ui->Lisen_btn->text() == "断开连接")
        {
            TcpSocket->disconnectFromHost();
            TcpSocket->close();
            ui->Lisen_btn->setText("连接");
            ui->NetMode_comboBox->setEnabled(true);
            delete TcpSocket;
            TcpSocket = nullptr;
            return;
        }
        TcpSocket = new QTcpSocket;
        connect(TcpSocket, &QTcpSocket::stateChanged, this, &MainWindow::onTcpSocketConnect);
        TcpSocket->connectToHost(ip, port);
        connect(TcpSocket, &QTcpSocket::readyRead, this, &MainWindow::NetWorkReadyRead);
    }
}

void MainWindow::on_NetSend_btn_clicked()
{
    if (ui->NetMode_comboBox->currentText() == "TcpServer")
    {
        onReadyWrite();
    }
    else if (ui->NetMode_comboBox->currentText() == "TcpClient")
    {
        int ret = TcpSocket->write(ui->networkSend_plainTextEdit->toPlainText().toUtf8());
        if (ret)
            NetWorkTXTolalCnt += ret;
        ui->NetTX->setText(QString("TX:%1").arg(NetWorkTXTolalCnt));
    }
}


void MainWindow::on_CleanNetReceive_btn_clicked()
{
    ui->network_plainTextEdit->clear();
}

void MainWindow::on_ChoseFile_btn_clicked()
{
    // 打开保存文件对话框，让用户选择文件名和路径
    QString fileName = QFileDialog::getOpenFileName(this, tr("从本地读取"), QDir::homePath(), tr("Text Files (*.txt);;All Files (*)"));

    if (!fileName.isEmpty())
    {
        // 用户选择了文件名和路径，现在可以在这里写入文件
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            ui->networkSend_plainTextEdit->setPlainText(in.readAll());
            file.close();
        }
        else
        {
            QMessageBox::warning(this, tr("错误"), tr("无法打开文件进行读取:\n%1").arg(fileName));
        }
    }
}

void MainWindow::on_NetCleanSend_btn_clicked()
{
    ui->networkSend_plainTextEdit->clear();
}

void MainWindow::on_NetMode_comboBox_activated(const QString &arg)
{
    if (arg == "TcpServer")
    {
        msgbox("server mode");
        ui->Lisen_btn->setText("监听");
    }
    else
    {
        msgbox("client mode");
        ui->Lisen_btn->setText("连接");
    }
}

void MainWindow::on_NextWorkFind_checkBox_stateChanged(int arg)
{
    if (arg == 0)
    {
        ChangeReceivePlainTextEditAllStringColor(ui->network_plainTextEdit);//恢复颜色
    }
    if (arg && ui->NextWorkFind_checkBox->text().size()>0)
    {
        ChangeReceivePlainTextEditSubStringColor(ui->network_plainTextEdit, ui->NetWorkFind_lineEdit);
    }
}
